package com.it.machine.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.it.machine.mapper.MachineActivationMapper;
import com.it.machine.domain.MachineActivation;
import com.it.machine.service.IMachineActivationService;
import com.it.machine.domain.ActivationCode;
import com.it.machine.service.IActivationCodeService;

/**
 * 激活电脑Service业务层处理
 * 
 * @author 云淡风轻
 * @date 2025-04-28
 */
@Service
public class MachineActivationServiceImpl implements IMachineActivationService 
{
    @Autowired
    private MachineActivationMapper machineActivationMapper;
    
    @Autowired
    private IActivationCodeService activationCodeService;

    /**
     * 查询激活电脑
     * 
     * @param id 激活电脑主键
     * @return 激活电脑
     */
    @Override
    public MachineActivation selectMachineActivationById(Long id)
    {
        return machineActivationMapper.selectMachineActivationById(id);
    }

    /**
     * 查询激活电脑列表
     * 
     * @param machineActivation 激活电脑
     * @return 激活电脑
     */
    @Override
    public List<MachineActivation> selectMachineActivationList(MachineActivation machineActivation)
    {
        List<MachineActivation> list = machineActivationMapper.selectMachineActivationList(machineActivation);
        
        // 实时对比当前时间与过期时间来判断过期状态
        Date now = new Date();
        for (MachineActivation activation : list) {
            // 如果状态不是禁用状态(3)且有过期时间，则进行实时判断
            if (activation.getStatus() != 3 && activation.getExpireTime() != null) {
                // 如果当前时间已超过过期时间，则设置为过期状态
                if (now.after(activation.getExpireTime())) {
                    activation.setStatus(2); // 已过期
                }
            }
        }
        
        return list;
    }

    /**
     * 新增激活电脑
     * 
     * @param machineActivation 激活电脑
     * @return 结果
     */
    @Override
    public int insertMachineActivation(MachineActivation machineActivation)
    {
        return machineActivationMapper.insertMachineActivation(machineActivation);
    }

    /**
     * 修改激活电脑
     * 
     * @param machineActivation 激活电脑
     * @return 结果
     */
    @Override
    public int updateMachineActivation(MachineActivation machineActivation)
    {
        return machineActivationMapper.updateMachineActivation(machineActivation);
    }

    /**
     * 批量删除激活电脑
     * 
     * @param ids 需要删除的激活电脑主键
     * @return 结果
     */
    @Override
    public int deleteMachineActivationByIds(Long[] ids)
    {
        return machineActivationMapper.deleteMachineActivationByIds(ids);
    }

    /**
     * 删除激活电脑信息
     * 
     * @param id 激活电脑主键
     * @return 结果
     */
    @Override
    public int deleteMachineActivationById(Long id)
    {
        return machineActivationMapper.deleteMachineActivationById(id);
    }

    /**
     * 验证激活码并激活机器
     * 
     * @param proId 项目ID
     * @param machineId 机器码
     * @param activeCode 激活码
     * @return 激活结果：0-成功，1-激活码不存在，2-激活码已使用，3-机器码不匹配，4-激活码已禁用
     */
    @Override
    public MachineActivation selectMachineActivationByCodeAndProId(String activeCode, String proId) {
        MachineActivation param = new MachineActivation();
        param.setProId(proId);
        param.setActiveCode(activeCode);
        return machineActivationMapper.selectMachineActivationByCodeAndProId(param.getActiveCode(), param.getProId());
    }
    
    @Override
    public MachineActivation selectMachineActivationByMachineIdAndProId(String machineId, String proId) {
        return machineActivationMapper.selectMachineActivationByMachineIdAndProId(machineId, proId);
    }
    
    @Override
    public MachineActivation selectMachineActivationByProIdAndMachineId(String proId, String machineId) {
        MachineActivation activation = machineActivationMapper.selectMachineActivationByProIdAndMachineId(proId, machineId);
        if (activation != null) {
            // 实时检查激活是否过期
            Date now = new Date();
            if (activation.getStatus() != 3 && activation.getExpireTime() != null && now.after(activation.getExpireTime())) {
                activation.setStatus(2); // 已过期
            }
        }
        return activation;
    }
    
    @Override
    public int verifyAndActivate(String proId, String machineId, String activeCode) {
        // 1. 首先获取激活码信息
        ActivationCode codeInfo = activationCodeService.selectActivationCodeByCode(activeCode);
        if (codeInfo == null) {
            return 1; // 激活码不存在
        }
        
        // 2. 验证激活码是否适用于当前项目
        if (!codeInfo.getProId().equals(proId)) {
            return 6; // 激活码与项目不匹配
        }
        
        // 3. 检查激活码状态
        if (codeInfo.getStatus() == 1L) {
            // 4. 激活码已使用，检查是否与当前机器绑定
            MachineActivation existingActivation = selectMachineActivationByProIdAndMachineId(proId, machineId);
            if (existingActivation != null) {
                // 4.1 如果存在机器绑定记录
                if (existingActivation.getActiveCode() != null && existingActivation.getActiveCode().equals(activeCode)) {
                    // 4.1.1 激活码匹配，激活成功
                    return 0;
                } else {
                    // 4.1.2 激活码不匹配
                    return 3;
                }
            }
        } else if (codeInfo.getStatus() == 2L) {
            // 5. 激活码已禁用
            return 4;
        }
        
        // 6. 检查项目是否需要机器码限制
        if (codeInfo.getMachineRestricted() != null && codeInfo.getMachineRestricted() == 1) {
            // 6.1 项目需要机器码限制，检查当前项目已激活的机器数量
            int activatedMachineCount = machineActivationMapper.countActivatedMachinesByProId(proId);
            
            // 6.2 检查是否超出最大可激活机器数量
            if (codeInfo.getMaxMachineCount() != null && activatedMachineCount >= codeInfo.getMaxMachineCount()) {
                return 7; // 超出项目最大可激活机器数量
            }
        }
        
        // 7. 创建新的机器激活记录或更新现有记录
        MachineActivation activationRecord = new MachineActivation();
        activationRecord.setProId(proId);
        activationRecord.setProName(codeInfo.getProName());
        activationRecord.setMachineId(machineId);
        activationRecord.setActiveCode(activeCode);
        activationRecord.setCurrentMark(codeInfo.getMark().intValue());
        activationRecord.setActiveTime(new Date());
        activationRecord.setStatus(1); // 已激活
        activationRecord.setCreateTime(new Date());
        
        // 8. 计算结束时间（如果不是永久）
        if (!"permanent".equals(codeInfo.getValidityType()) && codeInfo.getValidityValue() != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            
            switch (codeInfo.getValidityType()) {
                case "minute":
                    cal.add(Calendar.MINUTE, codeInfo.getValidityValue().intValue());
                    break;
                case "hour":
                    cal.add(Calendar.HOUR_OF_DAY, codeInfo.getValidityValue().intValue());
                    break;
                case "day":
                    cal.add(Calendar.DAY_OF_MONTH, codeInfo.getValidityValue().intValue());
                    break;
                case "month":
                    cal.add(Calendar.MONTH, codeInfo.getValidityValue().intValue());
                    break;
                case "year":
                    cal.add(Calendar.YEAR, codeInfo.getValidityValue().intValue());
                    break;
            }
            
            activationRecord.setExpireTime(cal.getTime());
        }
        
        // 9. 保存机器激活记录
        machineActivationMapper.insertMachineActivation(activationRecord);
        
        // 10. 更新激活码状态为已使用
        codeInfo.setStatus(1L); // 1表示已使用
        activationCodeService.updateActivationCode(codeInfo);
        
        return 0; // 激活成功
    }
    


    /**
     * 生成机器码
     * @return 机器码
     */
    private String generateMachineCode() {
        return UUID.randomUUID().toString().replaceAll("-", "").toUpperCase().substring(0, 24);
    }
    
    @Override
    public int disableMachineActivation(Long id) {
        MachineActivation activation = new MachineActivation();
        activation.setId(id);
        activation.setStatus(2); // 设置为禁用状态
        return machineActivationMapper.updateMachineActivation(activation);
    }
    
    @Override
    public int enableMachineActivation(Long id) {
        MachineActivation activation = selectMachineActivationById(id);
        if (activation != null) {
            // 启用时，需要重新判断是否过期
            Date now = new Date();
            if (activation.getExpireTime() != null && now.after(activation.getExpireTime())) {
                activation.setStatus(3); // 如果已过期，则设置为过期状态
            } else {
                activation.setStatus(1); // 否则设置为已激活状态
            }
            return machineActivationMapper.updateMachineActivation(activation);
        }
        return 0;
    }
}
